package com.zhai.netty.book.chapter04.demoin;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeServerHandler042 extends ChannelHandlerAdapter{
	
	private int counter;
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		ByteBuf buf = (ByteBuf)msg;
		byte[] req  = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body= new String(req,"UTF-8");
		System.out.println("------------------server read msg :--------------------------");
		System.out.println(body + "; 当前count值是 : "+ ++counter);
		
		/**
		 * copiedBuffer:
		 * 创建一个新的big-endian缓冲区，其内容是特定数组的副本。新缓冲区的readerIndex和writerIndex是0和array。长度分别为
		 */
		Unpooled.buffer();
		ByteBuf responseMsg = Unpooled.copiedBuffer("服务器端已经收到你的消息".getBytes());
		ctx.writeAndFlush(responseMsg);
	}
	
	
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		System.err.println("服务器端拦截异常");
		super.exceptionCaught(ctx, cause);
	}
}
